package site.wanjiahao;

import java.util.Iterator;

// 抽取公共方法
public abstract class AbstractList<E> implements List<E> {

    protected int size;

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean contains(E ele) {
        return indexOf(ele) != NOT_FOUND_ELEMENT;
    }

    /**
     * 迭代器接口
     */
    public class DefaultIter implements Iterator<E> {

        private int point;

        @Override
        public boolean hasNext() {
            return point != size;
        }

        @Override
        public E next() {
            return get(point++);
        }
    }

    protected void rangeCheckForAdd(int index) {
        if (index < 0 || index > size) {
            // 不合法
            outOfBound(index);
        }
    }

    protected void rangeCheck(int index) {
        if (index < 0 || index >= size) {
            // 不合法
            outOfBound(index);
        }
    }

    protected void outOfBound(int index) {
        throw new ArrayIndexOutOfBoundsException("size: " + size + ", index: " + index);
    }

}
